package com.geping.etl.common.service.kettle.impl;


import com.geping.etl.common.dto.KettleRunResultDto;
import com.geping.etl.common.service.kettle.RunPathService;
import com.geping.etl.common.service.kettle.RunPathServiceDispatcher;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author pengcheng.peng
 * @Date 2021/7/29 15:46
 * @Version 1.0
 */
@Service
@Slf4j
public class CmdRunPathServiceImpl extends RunPathServiceDispatcher implements RunPathService {

    @Value("${log.path}")
    private String dir;

    @Override
    public KettleRunResultDto runPath(String pathname) {
        BufferedReader bufrError = null;
        BufferedWriter bw = null;
        Process ps = null;
        String batPath = pathname.replaceAll("\\\\", "/");
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        try {
            // 执行命令, 返回一个子进程对象（命令在子进程中执行）
            ps = Runtime.getRuntime().exec(batPath);

            // 方法阻塞, 等待命令执行完成（成功会返回0）
           // ps.waitFor();
            String fileName = date + "_RunBatchLog.txt";
            String p = dir + File.separator + fileName;
            String path = p.replaceAll("\\\\", "/");
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出（PS: 子进程的输出就是主进程的输入）
            bufrError = new BufferedReader(new InputStreamReader(ps.getErrorStream()));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            // 读取输出
            String line = null;
            while ((line = bufrError.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufrError != null) {
                try {
                    bufrError.close();
                } catch (Exception e) {

                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 销毁子进程
            if (ps != null) {
                ps.destroy();
            }
        }
        return KettleRunResultDto.results("调用脚本成功，请查看结果!");
    }

    @Override
    public boolean canRun(String pathname) {
        return pathname.endsWith(".bat")||pathname.endsWith(".sh");
    }
}
